<?php
namespace Common\Model;

class SiterServiceModel extends UserModel {
    const TYPE = 3; //3表示站长客服

    public function save2($d) {
        $d['type'] = self::TYPE;
        $d['recommend_income_scale'] = empty($d['recommend_income_scale']) ? 0 : (float)$d['recommend_income_scale'];  //站长客服提成

        try {
            return parent::save2($d);
        } catch(Exception $e) {
            throw new ThinkException($e->getMessage());
        }
    }

    /**
     * buildSearchExpr 
     * 组装查询条件
     * 
     * @param mixed $d  查询数据，一般来源于$_GET或$_POST
     * @param mixed $field  可查询的字段对照表，其结构为array(array('表单项目名称' => '数据库字段名称'))
     * @access public
     * @return void 返回值为数组，参见方法内部注释
     */
    public function buildSearchExpr($d, $field = NULL) {
        $expr = array();
        $dao  = array();
        $sortExpr = 'daymoney DESC';

        /**
         * 下标为表单中的项目名称，值为数据库中表的字段名称 
         */
        if(empty($field)) {
            $field = array(
                'uid'             => 'uid',
                'user_name'       => 'user_name',
                'status'          => 'status',
                'email'           => 'email',
                'service_id'      => 'service_id',
                'referr'          => 'referr',
                'qq'              => 'qq',
                'add_day'         => 'reg_time',        //form中使用键reg_day，在url中reg会被转义成注册商标的标志字符
                'last_login_day'  => 'last_login_time',
                'limit_ad_domain' => 'limit_ad_domain',
                'recommend'       => 'recommend',       //推荐人
            );
        }

        foreach($field as $k => $v) {
            $tmpExpr = null;
            $val     = isset($d[$k]) ? trim($d[$k]) : '';

            if(strlen($val) < 1) {
                continue;
           }

            switch($k) {
                case 'user_name' :
                    $expr['user_name'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                case 'email' : 
                    $expr['email'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                case 'qq':
                    $expr['qq'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                case 'referr' :
                    $expr['referr'] = array('EXP', "LIKE '%{$val}%'");
                    break;

                case 'add_day' : 
                    $tmpExpr = "TO_CHAR(reg_time, 'YYYY-MM-DD') = '{$val}'";
                    break;

                case 'last_login_day' : 
                    $tmpExpr = "TO_CHAR(last_login_time, 'YYYY-MM-DD') = '{$val}'";
                    break;

                default:
                    $expr[$v] = $d[$k];
            }

            if(!empty($tmpExpr)) {
                $expr['_string'] = empty($expr['_string'])
                                  ? $tmpExpr
                                  : $expr['_string'] . " AND {$tmpExpr}";
            }

            $dao[$k] = $d[$k];
        }

        $sortField = array('uid', 'user_name', 'money', 'daymoney', 'weekmoney', 'monthmoney', 'status',
                            'last_login_time', 'login_num', 'service_id', 'limit_ad_domain', 'recommend');

        if(!empty($d['sort']) && in_array($d['sort'], $sortField)) {
            $sortdir = empty($d['sortdir'])                     ? 'DESC'   : strtoupper($d['sortdir']);
            $sortdir = in_array($sortdir, array('DESC', 'ASC')) ? $sortdir : 'DESC';

            if($d['sort'] == 'money') {
                $sort        = '(daymoney+weekmoney+monthmoney)';
                $dao['sort'] = 'money';
            } else {
                $sort        = $d['sort'];
                $dao['sort'] = $sort;
            }

            $sortExpr       = "{$sort} {$sortdir}";
            $dao['sortdir'] = $sortdir;
        }

        $expr['type'] = static::TYPE;

        return array(
            'expr' => $expr,            //ThinkPHP查询条件表达式
            'sort' => $sortExpr,        //排序表达式
            'json' => json_encode($dao) //用于回填至查询表单的数据
        );
    }

    public function getByUid($uid) {
        $expr = array(
            'type' => self::TYPE,
            'uid'  => $uid,
        );

        return $this->where($expr)->find();
    }

    /**
     * del
     *
     * @param mixed $id
     * @return void
     */
    public function del($id) {
        $id = (int)$id;

        $expr = array(
            'type' => self::TYPE,
            'uid'  => $id,
        );

        return $this->where($expr)->delete();
    }

    protected function _options_filter(&$options) {
        $options['where']         = isset($options['where']) ? $options['where'] : array();
        $options['where']['type'] = self::TYPE;
    }

    /**
     * getRandServiceId
     * 随机获取一个允许登陆的站长客服编号
     *
     * @return void
     */
    public function getRandServiceId() {
        if(!$record = $this->getAllowList()) {
            return false;
        }

        shuffle($record);
        $count = count($record);
        $index = mt_rand(0, $count-1);

        return $record[$index]['uid'];
    }

    /**
     * getAllowList
     * 返回允许登陆的站长客服记录
     *
     * @return void
     */
    public function getAllowList() {
        $expr = array('status' => 2);

        return ($record = $this->where($expr)->order('sex ASC')->select()) ? $record : false;
    }

}
